<template>
    <view class="comm-list-container">
        <!-- 使用PageHeader组件 -->
        <page-header title="土地整备记录"></page-header>

        <!-- 搜索栏 -->
        <view class="search-box">
            <uni-search-bar
                placeholder="请输入要搜索的内容"
                cancelButton="none"
                v-model="searchKey"
                @input="handleSearch"
                @confirm="handleSearch"
                :radius="100"></uni-search-bar>
        </view>

        <!-- 过滤标签 -->
        <filter-tabs :activeTab="selectedDateRange" @tab-change="handleFilterChange"></filter-tabs>

        <!-- 列表内容 -->
        <view class="comm-record-list">
            <record-item
                v-for="(item, index) in filteredLandRecords"
                :key="index"
                :item="item"
                @clickItem="editRecord(item)"
                @edit="editRecord(item)"
                @delete="confirmDelete(item)">
                <template #header>
                    <view class="item-header">
                        <text class="date-text">
                            {{ formatDate(item.startDate) }} 至 {{ formatDate(item.endDate) }}
                        </text>
                        <text class="date-text" style="color: rgba(39, 201, 93, 1)">
                            {{
                                getDictLabel('land_preparation', item.preparationContent) ||
                                item.preparationType
                            }}
                        </text>
                    </view>
                </template>

                <template #content>
                    <view class="item-content">
                        <view style="display: flex; justify-content: space-between">
                            <view class="info-row">
                                <text class="info-label text-nowrap">地块/条田</text>
                                <text class="info-value">
                                    {{ item.plotName }}-{{ item.fieldName }}
                                </text>
                            </view>
                            <view class="info-row">
                                <text class="info-label text-nowrap">负责人</text>
                                <text class="info-value text-nowrap">{{ item.manager }}</text>
                            </view>
                        </view>
                        <view class="info-row">
                            <text class="info-label">备注</text>
                            <text class="info-value">{{ item.remark }}</text>
                        </view>

                        <view class="info-columns">
                            <view class="info-column">
                                <text class="column-label">整备面积</text>
                                <text class="column-value">{{ item.area }} 亩</text>
                            </view>
                        </view>

                        <view class="item-images" v-if="item.image">
                            <image :src="item.image" mode="aspectFit"></image>
                        </view>
                    </view>
                </template>
            </record-item>

            <!-- 加载更多提示 -->
            <view class="load-more-container" v-if="filteredLandRecords.length > 0">
                <view v-if="loadingMore" class="loading-more">
                    <text class="loading-text">加载中...</text>
                </view>
                <view v-else-if="!hasMore" class="no-more">
                    <text class="no-more-text">没有更多数据了</text>
                </view>
            </view>
        </view>
        <!-- 使用EmptyData组件代替原有的空数据显示 -->
        <empty-data v-if="filteredLandRecords.length === 0" text="暂无土地整备记录" />
        <!-- 新增按钮 -->
        <view
            class="add-button"
            @click="navigateTo('/pages/agriculture/landPreparation/addLandPreparation')">
            <text class="add-icon">+</text>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import FilterTabs from '@/components/FilterTabs/index.vue'
import RecordItem from '@/components/RecordItem/index.vue'
import EmptyData from '@/components/EmptyData/index.vue'
import { land } from '@/utils/api/index.js'
import { formatDate, formatImages } from '@/utils/util.js'
import { mapGetters } from 'vuex'

export default {
    components: {
        PageHeader,
        FilterTabs,
        RecordItem,
        EmptyData,
    },
    data() {
        return {
            searchKey: '',
            selectedDateRange: 'all',
            landRecords: [],
            loading: false,
            loadingMore: false,
            hasMore: true,
            pageParams: {
                pageNo: 1,
                pageSize: 30,
            },
        }
    },
    onShow() {
        // 每次显示页面时刷新数据
        this.fetchLandRecords()
    },
    // 下拉刷新
    onPullDownRefresh() {
        this.fetchLandRecords()
    },
    // 触底加载更多
    onReachBottom() {
        this.loadMoreData()
    },
    computed: {
        ...mapGetters({
            getDictLabel: 'getDictLabel',
        }),
        filteredLandRecords() {
            return this.landRecords
        },
    },
    methods: {
        navigateTo(url) {
            uni.navigateTo({
                url,
            })
        },

        // 处理搜索变化
        handleSearch(e) {
            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 更新关键词搜索参数
            if (this.searchKey) {
                this.pageParams.keyword = e || this.searchKey
            } else {
                delete this.pageParams.keyword
            }

            // 重新请求接口
            this.fetchLandRecords()
        },

        // 处理筛选变化
        handleFilterChange(tabValue, filterData) {
            this.selectedDateRange = tabValue

            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 清除之前的日期和地块筛选条件
            delete this.pageParams.startDate
            delete this.pageParams.endDate
            delete this.pageParams.plotId

            // 添加新的筛选条件
            if (filterData) {
                if (filterData.startDate && filterData.endDate) {
                    this.pageParams.startDate = filterData.startDate
                    this.pageParams.endDate = filterData.endDate
                }

                if (filterData.areaId) {
                    this.pageParams.plotId = filterData.areaId
                }
            }

            // 重新请求接口
            this.fetchLandRecords()
        },

        async fetchLandRecords(isLoadMore = false) {
            if (isLoadMore) {
                this.loadingMore = true
            } else {
                this.loading = true
                uni.showLoading({ title: '加载中...' })
            }

            try {
                const res = await land.getLandPreparationList(this.pageParams)

                if (res.code === 0 && res.data) {
                    // 转换数据格式
                    const newList = res.data.list.map((item) => {
                        // 处理日期显示
                        const startDate = item.startDate
                        const endDate = item.endDate

                        return {
                            id: item.id,
                            startDate: startDate,
                            endDate: endDate,
                            land: item.plotName || item.plotId,
                            area: item.area,
                            type: item.preparationContent,
                            manager: item.personInCharge,
                            image: item.images ? formatImages(item.images)[0] : null,
                            createTime: item.createTime,
                            remark: item.remark,
                            plotName: item.plotName,
                            fieldName: item.fieldName,
                            preparationContent: item.preparationContent,
                        }
                    })

                    if (isLoadMore) {
                        // 加载更多时追加数据
                        this.landRecords = [...this.landRecords, ...newList]
                        // 判断是否还有更多数据
                        this.hasMore = newList.length >= this.pageParams.pageSize
                    } else {
                        // 首次加载或刷新时替换数据
                        this.landRecords = newList
                        this.hasMore = newList.length >= this.pageParams.pageSize
                    }
                } else {
                    if (!isLoadMore) {
                        this.landRecords = []
                        uni.showToast({
                            title: '获取数据失败',
                            icon: 'none',
                        })
                    }
                }
            } catch (error) {
                console.error('加载记录失败:', error)
                if (!isLoadMore) {
                    uni.showToast({
                        title: '加载数据失败',
                        icon: 'none',
                    })
                    this.landRecords = []
                }
            } finally {
                this.loading = false
                this.loadingMore = false
                uni.hideLoading()
                uni.stopPullDownRefresh()
            }
        },

        formatDate(date) {
            return formatDate(date)
        },

        editRecord(item) {
            uni.navigateTo({
                url: `/pages/agriculture/landPreparation/addLandPreparation?id=${item.id}`,
            })
        },

        async confirmDelete(item) {
            uni.showModal({
                title: '提示',
                content: `确定要删除此记录吗？`,
                success: async (res) => {
                    if (res.confirm) {
                        try {
                            uni.showLoading({ title: '删除中...' })
                            const result = await land.deleteLandPreparation(item.id)

                            if (result.code === 0) {
                                uni.showToast({
                                    title: '删除成功',
                                    icon: 'success',
                                })
                                // 重新加载数据
                                this.fetchLandRecords()
                            } else {
                                uni.showToast({
                                    title: result.msg || '删除失败',
                                    icon: 'none',
                                })
                            }
                        } catch (error) {
                            console.error('删除失败:', error)
                            uni.showToast({
                                title: '删除失败',
                                icon: 'none',
                            })
                        } finally {
                            uni.hideLoading()
                        }
                    }
                },
            })
        },

        // 加载更多数据
        loadMoreData() {
            if (this.loadingMore || !this.hasMore) {
                return
            }

            this.pageParams.pageNo += 1
            this.fetchLandRecords(true)
        },
    },
}
</script>

<style lang="scss"></style>
